package kordegi.forumsystem.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author kordegi
 * @date 2022.05.01 20:45
 * @Description
 */

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "kordegi.jwt")
public class JwtUtils {

    private long expireTime;
    private String secret;

    private String header;

    public String createToken(long id) {
        Date now = new Date();
        Date expire = new Date(now.getTime() + expireTime * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(id + "")
                .setIssuedAt(now)
                .setExpiration(expire)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Claims getClaimsByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJwt(token)
                    .getBody();
        } catch (Exception e) {
            log.error("token error", e);
            return null;
        }
    }

    public boolean isTokenExpired(Date expire) {
        return expire.before(new Date());
    }
}
